package com.tedu.jdbc;


import java.sql.*;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Scanner;


/**
 * Author：毕龙
 * Date: 2023/7/21 9:12
 */
public class TestJDBCConnection6 {
    public static void main(String[] args) throws ParseException {

        System.out.println("请输入修改的内容");
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入id：");
        int id = sc.nextInt();
        System.out.println("请输入name：");
        String username = sc.next();
        System.out.println("请输入pass：");
        String password = sc.next();
        System.out.println("请输入出生日期：");
        String birthday = sc.next();
        System.out.println("请输入创建时间：");
        String createTime = sc.next();
        //将字符串转化为时间日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date = sdf.parse(birthday);
        java.util.Date date1 = sdf.parse(createTime);


        try {
            update(new User(id,username,password,date,date1));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public static void update(User user) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取链接  java访问数据库的一个协议

        String url = "jdbc:mysql://localhost:3306/db4";
        Connection conn = DriverManager.getConnection(url, "root", "root");

        //3.执行sql语句
        String sql = "update user set username = ?,password=?,birthday=?,create_time = ? where id = ?";
        //获取PreparedStatement语句
        PreparedStatement pstm = conn.prepareStatement(sql);
        pstm.setString(1, user.getUsername());
        pstm.setString(2, user.getPassword());
        //将util.Date改成sql.Date

        pstm.setDate(3,new Date(user.getBirthday().getTime()));
        pstm.setDate(4,new Date(user.getCreateTime().getTime()));
        pstm.setInt(5, user.getId());

        int i = pstm.executeUpdate();
        if(i != 0 ){
            System.out.println("修改成功！");
        }

        //4.关闭资源
        pstm.close();
        conn.close();


    }
}
